<?php

namespace backend\modules\supplier\models\form;

use Yii;
use yii\base\Model;
use \common\models\goods\Goods;
use \common\models\product\Product;
use backend\modules\supplier\models\StorageIn;
use backend\modules\supplier\models\StorageInDetail;

/**
 * 入库单表单页
 */
class StorageInForm extends Model {

    public $isNewRecord;
    public $modelName = '入库单';
    public $id;
    public $sn;
    public $status;
    public $relate_id;
    public $relate_type;
    public $remark;
    public $detail;

    /**
     * @return array the validation rules.
     */
    public function rules() {
        return [
            [['sn'], 'required'],
            [['id', 'status', 'relate_id', 'relate_type'], 'integer'],
            [['remark'], 'string', 'max' => 45],
        ];
    }

    public function init() {
        parent::init();
        $this->detail = [new StorageInDetail];
    }

    /**
     * @return array customized attribute labels
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'sn' => '编号',
            'status' => '状态',
            'remark' => '备注',
            'detail' => '货品',
        ];
    }

    public function load($data, $formName = null) {
        //检查数据有效性
        if (parent::load($data, $formName) == FALSE) {
            return false;
        }

        //导入货品信息
        if (isset($data['StorageInForm']['products'])) {
            $this->detail = [];
            foreach ($data['StorageInForm']['products']['sn'] as $key => $sn) {
                $num = $data['StorageInForm']['products']['number'][$key];
                $price = $data['StorageInForm']['products']['price'][$key];
                $remark = $data['StorageInForm']['products']['remark'][$key];
                $id = $data['StorageInForm']['products']['id'][$key];

                if (empty($sn)) {
                    $this->addError('detail', "货品编号为空！");
                    return FALSE;
                }
                if (empty($num)) {
                    $this->addError('detail', "编号为：{$sn},入库数量为空！");
                    return FALSE;
                }
                if (empty($price)) {
                    $this->addError('detail', "编号为：{$sn},货品价格为空！");
                    return FALSE;
                }

                //验证货品编号唯一
                $where = 'supplier_id=:supplier_id and sn=:sn';
                $param = [':supplier_id' => Yii::$app->user->identity->supplier_id, ':sn' => $sn];
                $product = Product::find()->where($where, $param)->one();

                if (!$product) {
                    $this->addError('detail', "编号为：{$sn},没有找到这个货品！");
                    return FALSE;
                }

                $this->detail[] = ['id' => $id, 'product' => $product, 'num' => $num, 'price' => $price, 'remark' => $remark,];
            }
        }

        return true;
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     * @param  string  $email the target email address
     * @return boolean whether the model passes validation
     */
    public function save() {
        if ($this->validate()) {
            $storageIn = intval($this->id) > 0 ? StorageIn::findOne($this->id) : new StorageIn;
            !$storageIn && $storageIn = new StorageIn;
            $storageIn->setAttributes([
                'remark' => $this->remark,
            ]);

            if ($storageIn->save()) {
                foreach ($this->detail as $item) {
                    $storageInDetail = $item['id'] > 0 ? StorageInDetail::find($item['id']) : new StorageInDetail;
                    !$storageInDetail && $storageInDetail = new StorageInDetail;
                }
            }

            return true;
        }
    }

    public function getInfo() {
        if (intval($this->id) <= 0) {
            return FALSE;
        }

        $goods = Goods::findOne($this->id);
        if (!$goods) {
            return false;
        }
        $this->setAttributes($goods->getAttributes());

        $goods->info && $this->desc = $goods->info->desc;

        $this->gallery = [];
        for ($i = 0; $i < 5; $i++) {
            if (isset($goods->gallery[$i])) {
                $this->gallery[] = ['id' => $goods->gallery[$i]->id, 'img' => $goods->gallery[$i]->img];
            } else {
                $this->gallery[] = ['id' => '', 'img' => ''];
            }
        }

        //加载货品
        $this->products = [];
        $p = $goods->products;
        if ($goods->products) {
            if ($this->goods_type > 0) {
                foreach ($p as $item) {
                    $this->products[$item->goods_attr] = $item;
                }
            } else {
                count($p) > 0 && $this->products[] = $p[0];
            }
        }

        if ($goods->sku) {
            foreach ($goods->sku as $item) {
                $this->sku[$item->attr_id][$item['attr_value']] = $item;
            }
        }
    }

}
